import * as Cesium from '@cesiumjs';
import * as g3xUtils from "@g3x/utils";

function destroyColorTexture(wrfbo) {
  const {
    _colorTexture,
    _depthStencilTexture
  } = wrfbo;
  var destroyed = _colorTexture && !_colorTexture.isDestroyed() && _colorTexture.destroy();
  if (!destroyed && _colorTexture) {
    _colorTexture.destroy = function() {
      console.log("ddd");
    };
    wrfbo._colorTexture = undefined;
  }
  wrfbo._depthStencilTexture = _depthStencilTexture && !_depthStencilTexture.isDestroyed() && _depthStencilTexture
    .destroy();
}

function destroyFramebuffer(wrfbo) {
  const {
    _framebuffer
  } = wrfbo;
  wrfbo._framebuffer = _framebuffer && !_framebuffer.isDestroyed() && _framebuffer.destroy();
}

function updateTexture(wrfbo, context, width, height) {
  wrfbo._colorTexture = new Cesium.Texture({
    'context': context,
    'width': width,
    'height': height,
    'pixelFormat': Cesium.PixelFormat.RGBA,
    'pixelDatatype': Cesium.PixelDatatype.UNSIGNED_BYTE
  });
  wrfbo._depthStencilTexture = new Cesium.Texture({
    'context': context,
    'width': width,
    'height': height,
    'pixelFormat': Cesium.PixelFormat.DEPTH_STENCIL,
    'pixelDatatype': Cesium.PixelDatatype.UNSIGNED_INT_24_8
  });
}

function resetWrfbo(wrfbo, context, width, height) {
  destroyColorTexture(wrfbo);
  destroyFramebuffer(wrfbo);
  updateTexture(wrfbo, context, width, height);
  wrfbo._framebuffer = new Cesium.Framebuffer({
    'context': context,
    'colorTextures': [wrfbo._colorTexture],
    'depthStencilTexture': wrfbo._depthStencilTexture,
    'destroyAttachments': false
  });
}

function updateWrfbo(wrfbo, context, width, height) {
  var _colorTexture = wrfbo._colorTexture;
  var needUpdate = !Cesium.defined(_colorTexture) || _colorTexture.width !== width || _colorTexture.height !== height;
  if (!Cesium.defined(wrfbo._framebuffer) || needUpdate) {
    resetWrfbo(wrfbo, context, width, height);
    wrfbo._textureChangedEvent.raiseEvent(wrfbo._colorTexture);
  }
}

// _wrfbo WrfboObject
var WrfboObject = function() {
  function WrfboObject() {
    this._framebuffer = undefined;
    this._colorTexture = undefined;
    this._textureChangedEvent = new Cesium.Event();
  }

  g3xUtils.g3x_defineClassProperties(WrfboObject, [{
    'key': "getTextureChangedEvent",
    'value': function getTextureChangedEvent() {
      return this._textureChangedEvent;
    }
  }, {
    'key': "update",
    'value': function update(context, width, height) {
      updateWrfbo(this, context, width, height);
    }
  }, {
    'key': "isDestroyed",
    'value': function isDestroyed() {
      return false;
    }
  }, {
    'key': 'destroy',
    'value': function destroy() {
      destroyColorTexture(this);
      destroyFramebuffer(this);
      return destroyObject(this);
    }
  }]);
  return WrfboObject;
}();

export default WrfboObject;
